package com.thitech.sif.ws.soap;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import com.thitech.sif.ReqAndResContext;
import com.thitech.sif.utils.log.LogFactory;
import com.thitech.sif.utils.log.SifLogger;

/**
 * 在应用中使用JWS2.0标准的WebService客户端如(SAPNetweaver,CXF,JAX-WS)
 * 调用远程的WebService，要记录WebService的请求和响应
 * 
 * @author shisheng.lian
 * @date 2014-7-16
 */
public class LogSOAPMessageJWSHandler implements SOAPHandler<SOAPMessageContext> {
	private SifLogger log = LogFactory.getLogger(getClass());
	
	public Set<QName> getHeaders() {
		return null;
	}

	public void close(MessageContext messageContext) {
	}

	public boolean handleFault(SOAPMessageContext soapContext) {
		this.log(soapContext);
		return true;
	}

	public boolean handleMessage(SOAPMessageContext soapContext) {
		this.log(soapContext);
		return true;
	}

	private void log(SOAPMessageContext context) {
		Boolean outboundProperty = (Boolean) context
				.get("javax.xml.ws.handler.message.outbound");
		String logMessage = null;
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			context.getMessage().writeTo(os);
			byte[] data = os.toByteArray();
			logMessage = new String(data, "UTF-8");
			os.flush();
		} catch (SOAPException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			if (null != os) {
				try {
					os.close();
				} catch (Exception e) {
					//ignore
				}
			}
		}
		if (outboundProperty != null && outboundProperty.booleanValue()) {// 输入
			ReqAndResContext.currentContext().setRequest(logMessage);
		} else {// 输出
			ReqAndResContext.currentContext().setResponse(logMessage);
		}
	}
}
